<template>
  <d2-container>
    <template slot="header">
      <el-form
        class="header-area"
        ref="indexForm"
        :model="indexForm"
        label-width="120px"
        style="height: auto"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="采购订单编码" prop="orderNo">
              <el-input type="text" v-model="indexForm.orderNo" placeholder="采购订单编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input type="text" v-model="indexForm.supplierName" placeholder="供应商名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="SPU商品名称" prop="productName">
              <el-input type="text" v-model="indexForm.productName" placeholder="SPU商品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="SKU商品名称" prop="productSkuName">
              <el-input type="text" v-model="indexForm.productSkuName" placeholder="SKU商品名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="采购状态" prop="status">
              <el-select v-model="indexForm.status" placeholder="全部" style="width: 100%;">
                <el-option label="全部" value></el-option>
                <el-option label="待采购" value="0"></el-option>
                <el-option label="采购中" value="1"></el-option>
                <el-option label="已采购" value="2"></el-option>
                <el-option label="已取消" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="创建时间" prop="time">
              <el-date-picker
                v-model="time"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
                align="right"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <div class="search-submit">
              <el-button type="primary" size="medium" @click="submitForm('indexForm')">查询</el-button>
              <el-button type="primary" plain size="medium" @click="resetForm('indexForm')">重置</el-button>
              <el-button type="primary" size="medium" plain @click="exportExcel()">导出</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </template>

    <!-- 主体部分 -->
    <template>
      <!-- 表格上方的按钮 -->

      <!-- 表格 -->
      <!-- 表格统一用 带边框、条纹间隔 的样式 -->

      <el-table
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >

        <el-table-column type="index" fixed label="序号" width="50"></el-table-column>
        <el-table-column prop="orderNo" label="采购订单编码" width="210"></el-table-column>
        <el-table-column prop="supplierName" label="供应商名称" width="110"></el-table-column>
        <el-table-column prop="productName" label="SPU商品" width="100"></el-table-column>
        <el-table-column prop="productSkuName" label="SKU商品" width="100"></el-table-column>
        <el-table-column prop="purchaseQuantity" label="采购数量" width="100"></el-table-column>
        <el-table-column prop="unitName" label="采购单位" width="80"></el-table-column>
        <el-table-column prop="purchasePrice" label="采购单价(元)" width="110"></el-table-column>
        <el-table-column prop="purchaseAmount" label="采购金额(元)" width="110"></el-table-column>
        <el-table-column prop="discountRate" label="折扣(%)" width="110" :formatter="formatPercent"></el-table-column>
        <el-table-column prop="purchaseAmountDiscount" label="折扣金额(元)" width="110"></el-table-column>
        <el-table-column prop="statusDesc" label="采购状态" width="80"></el-table-column>
        <el-table-column prop="stockInQuantity" label="已入库数量" width="100"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" :formatter="forDateCreateTime"></el-table-column>

        <el-table-column label="操作" fixed="right" width="100">
          <template slot-scope="scope">
            <el-button v-if="checkAuditedBtn(scope.row.status)"
              type="primary" plain size="small" @click.native.prevent="toStock(scope.row)"
            >去入库</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <template slot="footer">
      <div class="page">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </template>

  </d2-container>
</template>

<script>
import {
  getOrderDetailPage, exportPurchaseDetail
} from '@api/purchase/purchase'
import dayjs from 'dayjs'

export default {
  name: 'purchase-detailList',
  components: {
    // detailPage
  },
  data () {
    return {
      indexForm: {
        orderNo: '',
        supplierName: '',
        productName: '',
        productSkuName: '',
        status: '',
        startTime: '',
        endTime: ''
      },
      time: [],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      multipleSelection: [],
      detailComponent: false,

      // 去入库表单
      toStockForm: {
        id: '',
        supplierId: '',
        supplierCode: '',
        supplierName: '',
        orderNo: '',
        purchaseOrderDetailId: ''
      }
    }
  },

  mounted () {
    this.fetchData()
  },
  methods: {
    fetchData () {
      this.loading = true

      this.indexForm.startTime = this.time[0] == null ? '' : dayjs(this.time[0]).format('YYYY-MM-DD HH:mm:ss')
      this.indexForm.endTime = this.time[1] == null ? '' : dayjs(this.time[1]).format('YYYY-MM-DD HH:mm:ss')

      getOrderDetailPage({
        orderNo: this.indexForm.orderNo,
        supplierName: this.indexForm.supplierName,
        productName: this.indexForm.productName,
        productSkuName: this.indexForm.productSkuName,
        status: this.indexForm.status,
        startTime: this.indexForm.startTime,
        endTime: this.indexForm.endTime,

        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
        .then(res => {
          this.tableData = res.data.content
          this.total = res.data.total
          this.loading = false
        })
        .catch(err => {
          console.log('err', err)
          this.loading = false
        })
    },
    toStock (row) {
      if (row.status != 1) {
        this.$message({ message: '状态不是采购中，不允许入库', type: 'error' })
        return
      }

      this.toStockForm.id = row.orderId
      this.toStockForm.orderNo = row.orderNo
      this.toStockForm.supplierId = row.supplierId
      this.toStockForm.supplierCode = row.supplierCode
      this.toStockForm.supplierName = row.supplierName
      this.toStockForm.purchaseOrderDetailId = row.id

      sessionStorage.setItem('toStockInOrderAddFlag', 'fromPurchaseOrder')
      sessionStorage.setItem('stockInOrder_add_purchaseOrder', JSON.stringify(this.toStockForm))

      // console.log('stockInOrder_add_purchaseOrder', this.toStockForm);
      // console.log('stockInOrder_add_purchaseOrder', JSON.stringify(this.toStockForm));
      // console.log('stockInOrder_add_purchaseOrder', JSON.parse(this.toStockForm));

      this.$router.push({
        path: '/stockIn/purchaseStockInAdd'
      })
    },
    checkAuditedBtn (status) {
      if (status == 1) { // 采购中才允许入库
        return true
      }
    },
    exportExcel () {
      this.loading = true

      this.indexForm.startTime = this.time[0] == null ? '' : dayjs(this.time[0]).format('YYYY-MM-DD HH:mm:ss')
      this.indexForm.endTime = this.time[1] == null ? '' : dayjs(this.time[1]).format('YYYY-MM-DD HH:mm:ss')

      // console.info(JSON.stringify(queryForm))
      exportPurchaseDetail({
        orderNo: this.indexForm.orderNo,
        supplierName: this.indexForm.supplierName,
        productName: this.indexForm.productName,
        productSkuName: this.indexForm.productSkuName,
        status: this.indexForm.status,
        startTime: this.indexForm.startTime,
        endTime: this.indexForm.endTime,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
        .then(res => {
          var blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
          var filename = res.headers.filename
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) // 创建下载的链接
          downloadElement.style.display = 'none'
          downloadElement.href = href
          downloadElement.download = filename // 下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() // 点击下载
          document.body.removeChild(downloadElement) // 下载完成移除元素
          window.URL.revokeObjectURL(href) // 释放掉blob对象
          this.loading = false
        })
        .catch(err => {
          console.log('err', err)
          this.loading = false
        })
    },

    handleSizeChange (val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.fetchData()
    },
    forDate (row, column) {
      return row.createTime == null
        ? ''
        : dayjs(row.expectedArrivalTime).format('YYYY-MM-DD')
    },
    forDateCreateTime (row, column) {
      return row.createTime == null
        ? ''
        : dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    formatPercent (row, column) {
      return row.discountRate + '%'
    },
    resetPage () {
      this.currentPage = 1
      this.pageSize = 10
      this.total = 0
    },
    submitForm (formName) {
      this.resetPage()
      this.fetchData()
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.time = []
      this.resetPage()
      this.fetchData()
    },

    /** 双向绑定 start */
    detailChange () {
      this.detailComponent = !this.detailComponent
    },
    onDetailPageChange (val) {
      this.detailComponent = val // ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    idChange (val) {
      this.orderId = val
    },
    onIdChange (val) {
      this.orderId = val // ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },

    /** 双向绑定 end */
    // 操作用户状态
    operateUserStatus (row, status) {
      this.$confirm(
        '确认' +
          (status == 0 ? '激活' : '冻结') +
          ('【' + row.userName + '】？')
      ).then(_ => {
        this.loading = true
        operateUserStatus({
          id: row.id,
          status: status
        })
          .then(res => {
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.header-area {
  .el-row {
    .el-col {
      .el-form-item {
        margin-bottom: 20px;
      }
    }
    &:last-child {
      .el-col {
        .el-form-item {
          margin-bottom: 0;
        }
      }
    }
  }
}
</style>
